package org.example.lethear.repository;

import org.example.lethear.entity.UserProfile;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

/**
 * 用户资料数据访问接口
 */
@Repository
public interface UserProfileRepository extends JpaRepository<UserProfile, Long> {
    
    /**
     * 根据用户ID查找用户资料
     */
    Optional<UserProfile> findByUserId(Long userId);
    
    /**
     * 检查用户是否已有资料
     */
    boolean existsByUserId(Long userId);
    
    /**
     * 根据昵称查找用户资料
     */
    Optional<UserProfile> findByNickname(String nickname);
    
    /**
     * 检查昵称是否存在
     */
    boolean existsByNickname(String nickname);
    
    /**
     * 根据性别查找用户资料
     */
    List<UserProfile> findByGender(Integer gender);
    
    /**
     * 根据性别分页查找用户资料
     */
    Page<UserProfile> findByGender(Integer gender, Pageable pageable);
    
    /**
     * 根据生日范围查找用户
     */
    @Query("SELECT up FROM UserProfile up WHERE up.birthday BETWEEN :startDate AND :endDate")
    List<UserProfile> findByBirthdayBetween(@Param("startDate") LocalDate startDate, 
                                          @Param("endDate") LocalDate endDate);
    
    /**
     * 模糊搜索昵称
     */
    @Query("SELECT up FROM UserProfile up WHERE up.nickname LIKE %:keyword%")
    Page<UserProfile> searchByNickname(@Param("keyword") String keyword, Pageable pageable);
    
    /**
     * 查找有头像的用户
     */
    @Query("SELECT up FROM UserProfile up WHERE up.avatar IS NOT NULL AND up.avatar != ''")
    List<UserProfile> findUsersWithAvatar();
    
    /**
     * 查找有个人简介的用户
     */
    @Query("SELECT up FROM UserProfile up WHERE up.bio IS NOT NULL AND up.bio != ''")
    List<UserProfile> findUsersWithBio();
    
    /**
     * 统计各性别用户数量
     */
    @Query("SELECT up.gender, COUNT(up) FROM UserProfile up GROUP BY up.gender")
    List<Object[]> countByGender();
    
    /**
     * 查找今天生日的用户
     */
    @Query("SELECT up FROM UserProfile up WHERE MONTH(up.birthday) = MONTH(CURRENT_DATE) AND DAY(up.birthday) = DAY(CURRENT_DATE)")
    List<UserProfile> findUsersWithBirthdayToday();
    
    /**
     * 根据手机号查找用户（如果提供）
     */
    Optional<UserProfile> findByPhone(String phone);
    
    /**
     * 检查手机号是否存在
     */
    boolean existsByPhone(String phone);
} 